// 权限判断 因为有的接口请求头可能需要添加的参数不一样，所以这里做了区分power
// 1 == 登录携带请求头'custCode'
// 2 == 携带请求头token
import _ from 'lodash';
import baseUrl from './config';
const request = {globalRequest: null};
const queryUrl = ['/mobile/network/account/bindingPhone']; //put请求数据需要转换query string 在此处添加url
let isRefreshing = false;
// 获取刷token
function refreshToken(refresh, headers) {
	return new Promise((resolve, reject) => {
		uni
			.request({
				timeout: 100000,
				url: baseUrl + '/mobile/network/account/refreshToken',
				method: 'GET',
				data: {refreshToken: refresh},
				header: headers,
			})
			.then((res) => {
				resolve(res.data);
			});
	});
}

request.globalRequest = async (config) => {
	config.headers = {};
	config.method = config.method.toUpperCase(); //小写改为大写
	const datetime = new Date().getTime() / 1000;
	const dataValue = uni.getStorageSync('dd-access-network');
	const token = dataValue.token; //获取token值
	const tokenName = dataValue.tokenName; //token请求头
	const logintime = dataValue.logintime / 1000; //获取时登录时间戳
	const timeToken = dataValue.timeToken; //过期时间(秒)
	return new Promise(async (resolve, reject) => {
		switch (config.power) {
			case 1:
				break;
			case 2:
				config.headers[tokenName] = token;
				if (token) {
					if (queryUrl.includes(config.url)) {
						config.headers['content-type'] =
							'application/x-www-form-urlencoded'; //将数据转换为 query string
					}
					if (
						datetime - logintime > timeToken - 1800 &&
						datetime - logintime < timeToken
					) {
						// if ((datetime - logintime) > 10 && (datetime - logintime) < 20) {
						// 提前30之内分钟刷新token
						if (!isRefreshing) {
							isRefreshing = true;
							// 提前30之内分钟刷新token
							let res: any = await refreshToken(
								uni.getStorageSync('dd-access-network').refreshToken,
								{[tokenName]: token},
							);
							const logintime = new Date().getTime();
							let dataValueObj = {
								logintime: logintime, //当前登录时间戳
								token: res.data.row.tokenValue, // 设置token值
								refreshToken: res.data.row.refreshToken, //刷新token
								tokenName: res.data.row.tokenName, //token请求头
								timeToken: res.data.row.expireIn, //过期时间(秒)
								pws: dataValue.pws || '',
								phone: dataValue.phone || '',
							};
							config.headers[dataValueObj.tokenName] = dataValueObj.token;
							uni.setStorageSync('dd-access-network', dataValueObj);
							isRefreshing = false;
						}
					}
					if (datetime - logintime > timeToken) {
						// } if ((datetime - logintime) > 20) {
						uni
							.showModal({
								title: '提示',
								content: '您登录失效，请重新登录',
								showCancel: false,
							})
							.then((res) => {
								//确认
								if (res.confirm) {
									//关闭所有页面，打开到应用内的某个页面
									uni.reLaunch({
										url: '/pages/pages_network/login/login',
									});
									uni.removeStorageSync('dd-access-network');
									return reject();
								}
							});
						return reject();
					}
				}
				break;
		}

		let {url, method, data, isUpload, isFiles, headers} = config;
		let temp = null;
		if (!isUpload) {
			temp = uni.request({
				timeout: 100000,
				url: baseUrl + url,
				method: method,
				data: data,
				header: headers,
			});
		} else {
			if (isFiles) {
				temp = uni.uploadFile({
					url: baseUrl + url,
					formData: data,
					name: 'files',
					method: method,
					header: headers,
					filePath: data.files.path,
					timeout: 100000,
				});
			} else {
				temp = uni.uploadFile({
					url: baseUrl + url,
					formData: data,
					name: 'file',
					method: method,
					header: headers,
					filePath: data.files.path,
					timeout: 100000,
				});
			}
		}
		temp
			.then((res) => {
				if (isUpload) {
					res.data = JSON.parse(res.data);
				}
				if (
					res.data.code == 40011 ||
					res.data.code == 40100 ||
					res.data.code == 40101
				) {
					uni.hideLoading();
					uni
						.showModal({
							title: '提示',
							content: res.data.message,
							showCancel: false,
						})
						.then((res) => {
							//确认
							if (res.confirm) {
								//关闭所有页面，打开到应用内的某个页面
								uni.reLaunch({
									url: '/pages/pages_network/login/login',
								});
								//关闭所有页面，打开到应用内的某个页面
								uni.removeStorageSync('dd-access-network');
								return;
							}
						});
					resolve(res.data);
					return;
				}
				if (res.data.code == 61000 || res.data.code == 62000) {
					uni.hideLoading();
					uni.showModal({
						title: '提示',
						showCancel: false,
						confirmText: '知道了',
						confirmColor: '#007cff',
						content: res.data.message,
					});
					resolve(res.data);
					return;
				}
				if (!res.data.success) {
					uni.hideLoading();
					uni.showToast({
						title: res.data.message,
						duration: 4000,
						position: 'top',
						icon: 'none',
					});
				}
				resolve(res.data);
			})
			.catch((err) => {
				if (err.errMsg.includes('timeout')) {
					errFun('网络繁忙，请稍后重试！');
				} else if (err.errMsg.includes('network')) {
					errFun('网络异常');
				} else {
					errFun();
				}
				reject();
			});
	});
};
const errFun = _.throttle(
	(msg = '处理繁忙，请稍后重试！') => {
		uni.hideLoading();
		uni.showModal({
			title: '提示',
			showCancel: false,
			confirmText: '确认',
			confirmColor: '#007cff',
			content: msg,
		});
	},
	4000,
	{leading: false},
);

export default request;
